package com.example.exercise;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Looper;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.exercise.Base.SignBase;
import com.example.exercise.Base.User;
import com.example.exercise.MysqlUtil.DBService;
import com.example.exercise.MysqlUtil.FindExist;
import com.example.exercise.Utils.GetNetWorkTime;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Sign extends AppCompatActivity {


    ProgressDialog waitingDialog;
    private ImageView signin,load;
    private NfcAdapter mNfcAdapter;
    private PendingIntent pi;
    private TextView sn,sc,st,state,sclass;
    private String CardId = null;
    private User user;
    private CountDownTimer countDownTimer;
    private String noname,noclass;
    int yourChoice = -1;
    final String[] items = {"请选择班级","19物联网中本" ,"19电商中高职", "19国商" ,"19食品中高职" ,"19物联网" ,"20计网" ,"21物联网中本" ,"21电商中高职" ,"21移动互联中高"
            ,"21物流管理中高" ,"21食品中高职" ,"21粮油" ,"21通信" ,"20物联网中本" ,"20电商中高" ,"20学前" ,"20国商" ,"20食品中高" ,"20物联网" ,"20通信" ,"20电商精准扶贫"};
    private SignBase signBase ;
    SignBase signBase1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);
        sn  = findViewById(R.id.Signname);
        sc  =  findViewById(R.id.Signid);
        st  = findViewById(R.id.Signtime);
        signin = findViewById(R.id.signin);
        load =findViewById(R.id.load);
        state = findViewById(R.id.textView8);
        sclass =  findViewById(R.id.Signclass);

        countDownTimer = new CountDownTimer(3600000,1000) {
            @Override
            public void onTick(long l) {
                System.out.println("666距离关闭页面还有"+l/1000);
            }

            @Override
            public void onFinish() {
                    Intent intent = new Intent(getApplicationContext(),MainActivity.class);
                    startActivity(intent);
            }
        }.start();

        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (mNfcAdapter == null) {
            Toast.makeText(getApplicationContext(), "设备不支持NFC!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        if (!mNfcAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "请在系统设置中先启用NFC功能!", Toast.LENGTH_LONG).show();
            finish();
            return;
        }

       pi = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(getApplicationContext(), getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);                                                                                                                                   ;


        load.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                state.setText("");
                if (sc.getText().toString().trim().equals("")){
                    Toast.makeText(getApplicationContext(),"卡号不能为空",Toast.LENGTH_SHORT).show();
                }
                else {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {

                            final List<User> list = DBService.getUserName(CardId);
                            if (list.size() == 0) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        state.setText("读取失败，可能无卡号记录");
                                    }
                                });

                            } else {
                                if (FindExist.getUserLose(CardId).equals("是")){

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            state.setText("读取失败，该卡已挂失");
                                            sn.setText("");
                                            sc.setText("");
                                            sclass.setText("");
                                            st.setText("");
                                        }
                                    });

                                }else{


                                user = list.get(0);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        System.out.println(list.size() + "444");
                                        sn.setText(user.getName().toString());
                                        sclass.setText(user.getClassroom());
                                        Date date = new Date(System.currentTimeMillis());
                                        String simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH时mm分ss秒 ").format(date);
                                        st.setText(simpleDateFormat);


                                    }
                                });
                            }
                        }
                        }
                    }).start();

                }

            }
        });

        load.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                sn.setText("");
                sc.setText("");
                sclass.setText("");
                st.setText("");
                state.setText("");
                return true;
            }
        });

        signin.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                NoCard();
                return true;
            }
        });

        signin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (sc.getText().toString().trim().equals("")){

                    Toast.makeText(getApplicationContext(),"请先读取信息",Toast.LENGTH_SHORT).show();
                    state.setText("请先读取信息");
                }
                else if (sn.getText().toString().trim().equals("") || sc.getText().toString().equals("") || st.getText().toString().equals("") || sclass.getText().toString().equals("")){

                    Toast.makeText(getApplicationContext(),"不能为空",Toast.LENGTH_SHORT).show();
                    state.setText("不能为空");

                }
                else{
                    showWaitingDialog();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        SignBase signBase = new SignBase();
                        signBase.setTime(st.getText().toString());
                        signBase.setIfsign("是");
                        List<SignBase> list1 = new ArrayList<>();
                        list1.add(signBase);
                        if (list1.size() == 0){
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    state.setText("读取失败，可能无信息记录");
                                }
                            });
                        }else {
                                if (DBService.update1(list1,"否",sn.getText().toString()) != -1) {


                                    List<SignBase> list = DBService.getUserSign(sn.getText().toString());
                                    System.out.println("6666"+list.size());
                                    if (list.size() == 0){
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                waitingDialog.dismiss();
                                                state.setText("读取失败，可能无信息记录");
                                            }
                                        });
                                    }else{

                                        signBase1 = list.get(0);
                                        final SignBase finalSignBase = signBase1;
                                        System.out.println(finalSignBase.getName()+"66666");
                                        if (finalSignBase.getTime().equals("0")||finalSignBase.getIfsign().equals("今日无记录")){

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    waitingDialog.dismiss();
                                                    state.setText("录入失败，请重试");
                                                }
                                            });
                                        }else{

                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {

                                                    waitingDialog.dismiss();

                                                    Toast.makeText(getApplicationContext(), "签到成功", Toast.LENGTH_SHORT).show();
                                                    state.setText("签到成功");
                                                    sn.setText("");
                                                    sc.setText("");
                                                    sclass.setText("");
                                                    st.setText("");

                                                }
                                            });

                                            System.out.println("成功");
                                        }
                                    }
                                } else {
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {

                                            Toast.makeText(getApplicationContext(), "签到失败", Toast.LENGTH_SHORT).show();
                                            state.setText("签到失败");
                                        }
                                    });
                                }
                        }
                    }
                }).start();
                }
            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 当前app正在前端界面运行，这个时候有intent发送过来，那么系统就会调用onNewIntent回调方法，将intent传送过来
        // 我们只需要在这里检验这个intent是否是NFC相关的intent，如果是，就调用处理方法
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction())) {
            processIntent(intent);
        }
    }

    //启动
    @Override
    protected void onResume() {
        super.onResume();
        mNfcAdapter.enableForegroundDispatch(this, pi, null, null);
    }

    //解析
    private void processIntent(Intent intent) {
        //取出封装在intent中的TAG
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        CardId =ByteArrayToHexString(tagFromIntent.getId());
        sc.setText(CardId.toString());
        Toast.makeText(getApplicationContext(),CardId, Toast.LENGTH_LONG).show();
    }

    //转为16进制字符串
    private String ByteArrayToHexString(byte[] inarray) {
        int i, j, in;
        String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F" };
        String out = "";


        for (j = 0; j < inarray.length; ++j) {
            in = (int) inarray[j] & 0xff;
            i = (in >> 4) & 0x0f;
            out += hex[i];
            i = in & 0x0f;
            out += hex[i];
        }
        return out;
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(newBase);

    }


    @Override
    protected void onPause() {

        super.onPause();

    }

    @Override
    protected void onStop() {

        countDownTimer.cancel();
        Intent intent = new Intent(getApplicationContext(),MainActivity.class);
        startActivity(intent);

        super.onStop();
    }

    private void signNocard(final List<SignBase> list2){

                if (DBService.update2(list2,"是",noname) == 1)
                {
                    List<SignBase> list = DBService.getUsernoinsertSign(noname);
                    System.out.println("6666"+list.size());
                    if (list.size() == 0){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                waitingDialog.dismiss();
                                state.setText("读取失败，可能无信息记录");
                            }
                        });
                    }else {
                        signBase1 = list.get(0);
                        final SignBase finalSignBase = signBase1;
                        System.out.println(finalSignBase.getName()+"66666");
                        if (finalSignBase.getTime().equals("0")||finalSignBase.getIfsign().equals("今日无记录")){

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    waitingDialog.dismiss();
                                    state.setText("无卡签到失败，请重试");
                                }
                            });


                        }else{
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {


                                    state.setText("无卡签到成功");
                                }
                            });
                        }
                    }

                }else{

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            state.setText("无卡签到失败");
                        }
                    });

                }
    }

    private void showSingleChoiceDialog(){



            AlertDialog.Builder singleChoiceDialog =
                    new AlertDialog.Builder(Sign.this);
            singleChoiceDialog.setTitle("请选择班级");
            // 第二个参数是默认选项，此处设置为0
            singleChoiceDialog.setSingleChoiceItems(items, 0,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            yourChoice = which;
                        }
                    });
            singleChoiceDialog.setPositiveButton("确定",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (yourChoice != -1) {
                                noclass = items[yourChoice];


                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {

                                        if (FindExist.getUserName(noname,noclass) == 1){

                                            Date date = new Date(System.currentTimeMillis());
                                            String simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH时mm分ss秒 ").format(date);
                                            signBase = new SignBase();
                                            signBase.setName(noname);
                                            signBase.setClassroom(noclass);
                                            signBase.setTime(simpleDateFormat);
                                            signBase.setIfsign("是");
                                            System.out.println(signBase.getClassroom()+signBase.getName());
                                            Looper.prepare();
                                            showifuserexist();
                                            Looper.loop();
                                        }else{

                                            Looper.prepare();
                                            showifusernoexist();
                                            Looper.loop();
                                        }
                                    }
                                }).start();

                            }
                        }
                    });
            singleChoiceDialog.show();
    }

    private void showifusernoexist(){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(Sign.this);
        normalDialog.setTitle("用户库中不存在提醒");
        normalDialog.setMessage("姓名:"+noname+"  班级:"+noclass+"  库中无记录请确认信息是否正确，再决定是否签到");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        Date date = new Date(System.currentTimeMillis());
                        String simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH时mm分ss秒 ").format(date);
                        signBase = new SignBase();
                        signBase.setName(noname);
                        signBase.setClassroom(noclass);
                        signBase.setTime(simpleDateFormat);
                        signBase.setIfsign("是");
                        System.out.println(signBase.getClassroom()+signBase.getName());
                        final List<SignBase> list = new ArrayList<>();
                        list.add(signBase);
                        signNocard(list);


                    }
                });
        normalDialog.setNegativeButton("返回",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        InputName();
                    }
                });
        // 显示
        normalDialog.show();
    }

    private void showifuserexist(){
        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(Sign.this);
        normalDialog.setTitle("签到确认（库中有记录）");
        normalDialog.setMessage("姓名:"+noname+"  班级:"+noclass+"  正在无卡签到");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        showWaitingDialog();
                        final List<SignBase> list = new ArrayList<>();
                        list.add(signBase);
                        new  Thread(new Runnable() {
                            @Override
                            public void run() {

                             if (DBService.update1(list,"是",noname) == 1)
                             {
                                 List<SignBase> list = DBService.getUserSign(noname);
                                 System.out.println("6666"+list.size());
                                 if (list.size() == 0){
                                     runOnUiThread(new Runnable() {
                                         @Override
                                         public void run() {
                                             waitingDialog.dismiss();
                                             state.setText("读取失败，可能无信息记录");
                                         }
                                     });
                                 }else {
                                     signBase1 = list.get(0);
                                     final SignBase finalSignBase = signBase1;
                                     System.out.println(finalSignBase.getName()+"66666");
                                     if (finalSignBase.getTime().equals("0")||finalSignBase.getIfsign().equals("今日无记录")){

                                         runOnUiThread(new Runnable() {
                                             @Override
                                             public void run() {

                                                 waitingDialog.dismiss();
                                                 state.setText("无卡签到失败，请重试");
                                             }
                                         });


                                     }else{
                                         runOnUiThread(new Runnable() {
                                             @Override
                                             public void run() {

                                                 waitingDialog.dismiss();
                                                 state.setText("无卡签到成功");
                                             }
                                         });

                                     }
                                 }

                             }else{

                                 runOnUiThread(new Runnable() {
                                     @Override
                                     public void run() {
                                         waitingDialog.dismiss();
                                         state.setText("无卡签到失败");
                                     }
                                 });

                             }



                            }
                        }).start();

                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }

    private void  InputName() {
        /*@setView 装入一个EditView
         */

        final EditText editText = new EditText(Sign.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(Sign.this);
        inputDialog.setTitle("请输入名字").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (editText.getText().toString().trim().equals("")){
                            Toast.makeText(getApplicationContext(),
                                    "输入为空，重新输入",
                                    Toast.LENGTH_SHORT).show();
                            InputName();


                        }else {
                            noname = editText.getText().toString();
                            showSingleChoiceDialog();
                        }
                    }
                }).show();


    }

    private void NoCard() {

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(Sign.this);
        normalDialog.setTitle("你正在进行无卡签到");
        normalDialog.setMessage("请查验学生卡信息是否为本人");
        normalDialog.setPositiveButton("通过",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        InputName();

                    }
                });

        // 显示
        normalDialog.show();
    }

    private void showWaitingDialog() {
        /* 等待Dialog具有屏蔽其他控件的交互能力
         * @setCancelable 为使屏幕不可点击，设置为不可取消(false)
         * 下载等事件完成后，主动调用函数关闭该Dialog
         */
        waitingDialog=
                new ProgressDialog(Sign.this);
        waitingDialog.setTitle("正在录入");
        waitingDialog.setMessage("录入中，请务必联网");
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(false);
        waitingDialog.show();
    }
}